﻿using FlowServe.Models;
using Microsoft.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using static System.Net.Mime.MediaTypeNames;

namespace FlowServe.RemotingServer
{
    public class Remoting : IRemoting
    {
        private readonly IHttpClientFactory httpClientFactory;
        public List<WorkTask> workTasks=new List<WorkTask>();
        public bool mark { get; set; } = true;
        public bool IsStartTask { get; set ; }=true;//是否停止任务


        // 提取分钟和小时的正则表达式
       private string pattern = @"(?<seconds>\d+/\d+)\s+(?<minutes>\d+/\d+)";
        /// <summary>
        /// 
        /// </summary>
        /// <param name="httpClientFactory"></param>
        public Remoting(IHttpClientFactory httpClientFactory)
        {
            this.httpClientFactory = httpClientFactory;
        }
        public bool AddWork(WorkTask workTask)
        {
            try
            {
               if (workTasks.Any(o => o.ApiUir == workTask.ApiUir && o.Requestmethod == workTask.Requestmethod) == false)
                {
                    workTasks.Add(workTask);
                    if (workTasks.Any(o => o.runningstate))//有运行的任务
                    IsStartTask = true;
                    return true;
                }                     
            }
            catch (Exception ex)
            {
                //写错误日志
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                
            }
            return false;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public List<WorkTask> getRemotingWorks()
        {
            return workTasks;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public List<WorkTask> refreshWork()
        {
            return workTasks;
        }

        public bool tiggerActionWork(List<WorkTask> workTask)
        {
            if (workTasks.Count > 0 && workTasks.Any(o => o.runningstate))
                Parallel.ForEach(workTask.Where(o => o.runningstate), async o =>
            {
                if (o.runningstate==false) return;//结束本次
                try
                {
                    var httpClient = httpClientFactory.CreateClient();
                    if (o.Requestmethod == "GET")
                    {
                        var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, o.ApiUir);
                        if (o.header != null && o.header.Count > 0)
                            foreach (var item in o.header)
                            {
                                httpRequestMessage.Headers.Add(item.Key, item.Value);
                            }
                        var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
                        var contentstr = await httpResponseMessage.Content.ReadAsStringAsync();
                        if (httpResponseMessage.IsSuccessStatusCode)
                        {
                            //成功写日志
                        }
                        else
                        {
                            //错误写日志
                        }
                    }
                    else
                    {
                        var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, o.ApiUir);
                        if (o.header != null && o.header.Count > 0)
                            foreach (var item in o.header)
                            {
                                httpRequestMessage.Headers.Add(item.Key, item.Value);
                            }
                        httpRequestMessage.Content = new StringContent(string.IsNullOrWhiteSpace(o.Requestmethod) ? string.Empty : o.Requestmethod, Encoding.UTF8, Application.Json);
                        var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
                        var contentstr = await httpResponseMessage.Content.ReadAsStringAsync();
                        if (httpResponseMessage.IsSuccessStatusCode)
                        {
                            //成功写日志
                        }
                        else
                        {
                            //错误写日志
                        }
                    }
                }catch(Exception ex)
                {
                    //写错误日志
                    Console.WriteLine(ex.ToString());
                }
            });
            else
                IsStartTask = false;
            return true;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="workTask"></param>
        /// <returns></returns>
        public bool updateWork(WorkTask workTask)
        {
            if (workTasks.Any(o => o.ApiUir == workTask.ApiUir && o.Requestmethod == workTask.Requestmethod) == false)
            {
                workTasks.Add(workTask);
                if(workTasks.Any(o=>o.runningstate)) IsStartTask=true;
                else IsStartTask=false;
                return true;
            }       
            return false;
        }
        /// <summary>
        /// 执行任务
        /// </summary>
        public void tiggerWork()
        {
            if (workTasks.Count>0&& workTasks.Any(o=>o.runningstate))
            Parallel.ForEach(workTasks.Where(o=>o.runningstate&&TimetoTicks(o)), async o =>
            {
                try
                {
                    var httpClient = httpClientFactory.CreateClient();
                    if (o.Requestmethod == "GET")
                    {
                        var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, o.ApiUir);
                        if (o.header != null && o.header.Count > 0)
                            foreach (var item in o.header)
                            {
                                httpRequestMessage.Headers.Add(item.Key, item.Value);
                            }
                        var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
                        var contentstr = await httpResponseMessage.Content.ReadAsStringAsync();
                        if (httpResponseMessage.IsSuccessStatusCode)
                        {
                            //成功写日志
                        }
                        else
                        {
                            //错误写日志
                        }
                    }
                    else
                    {
                        var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, o.ApiUir);
                        if (o.header != null && o.header.Count > 0)
                            foreach (var item in o.header)
                            {
                                httpRequestMessage.Headers.Add(item.Key, item.Value);
                            }
                        httpRequestMessage.Content = new StringContent(string.IsNullOrWhiteSpace(o.Requestmethod) ? string.Empty : o.Requestmethod, Encoding.UTF8, Application.Json);
                        var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
                        var contentstr = await httpResponseMessage.Content.ReadAsStringAsync();
                        if (httpResponseMessage.IsSuccessStatusCode)
                        {
                            //成功写日志
                        }
                        else
                        {
                            //错误写日志
                        }
                    }
                }
                catch (Exception ex)
                {
                    //写错误日志
                    Console.WriteLine(ex.ToString());
                }

                o.Timestamp = DateTime.Now;
            });
            else
             IsStartTask=false;
        }
        private bool TimetoTicks(WorkTask data)
        {
            Match match = Regex.Match(data.timeinterval, pattern);

            if (match.Success)
            {
                string seconds = match.Groups["seconds"].Value;
                string minutes = match.Groups["minutes"].Value;
                // 这里假设日期为 2024-01-01，时分基于秒和分的字段（可调整逻辑以适应需求）
                string[] secondsParts = seconds.Split('/');
                int year = DateTime.Now.Year;
                int month = int.Parse(secondsParts[0])==0? data.Timestamp.Month: int.Parse(secondsParts[0]);
                int day = int.Parse(secondsParts[1]) == 0 ? data.Timestamp.Day : int.Parse(secondsParts[1]);

                // 提取分钟的偏移量（例如 "0/10" 提取出 10）
                string[] minutesParts = minutes.Split('/');
                int minuteOffset = int.Parse(minutesParts[1]);
                int hourOffset = int.Parse(minutesParts[0])==0?data.Timestamp.Hour: int.Parse(minutesParts[0]);
                // 构造下次执行的时间
                DateTime dateTime = new DateTime(year, month, day, hourOffset, minuteOffset, 0, DateTimeKind.Utc);

                // 转换为时间戳（Unix 时间）
                long timestamp = new DateTimeOffset(dateTime).ToUnixTimeSeconds();             
                return DateTime.Now>= dateTime;
            }
            else
            {
                return false;
            }
        }      
    }
}
